package cn.com.mall.product.service.impl;

import cn.com.mall.common.dto.SkuHasStockVo;
import cn.com.mall.common.dto.SkuReductionTo;
import cn.com.mall.common.dto.SpuBoundDTo;
import cn.com.mall.common.dto.es.SkuEsModel;
import cn.com.mall.common.utils.R;
import cn.com.mall.product.entity.*;
import cn.com.mall.product.feign.CouponFeignService;
import cn.com.mall.product.feign.SearchFeignService;
import cn.com.mall.product.feign.WareFeignService;
import cn.com.mall.product.service.*;
import cn.com.mall.product.vo.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jodd.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.com.mall.common.utils.PageUtils;
import cn.com.mall.common.utils.Query;

import cn.com.mall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    AttrService attrService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        String key=(String)params.get("key");
        String status=(String)params.get("status");
        String brandId=(String)params.get("brandId");
        String catelogId=(String)params.get("catelogId");
//        Long catelogId=(Long)params.get("catelogId");

        QueryWrapper<SpuInfoEntity> spuInfoEntityQueryWrapper = new QueryWrapper<>();


        if(!StringUtils.isEmpty(brandId) &&!"0".equals(brandId)){
            spuInfoEntityQueryWrapper.eq("brand_id",brandId);
        }

        if(!StringUtils.isEmpty(catelogId) &&!"0".equalsIgnoreCase(catelogId)){
            spuInfoEntityQueryWrapper.eq("catalog_id",catelogId);

        }
        if(!StringUtils.isEmpty(key)){
            spuInfoEntityQueryWrapper.and(item->{
                item.like("spu_name",key).or().like("spu_description",key);
            });

        }
        if(!StringUtils.isEmpty(status)){
            spuInfoEntityQueryWrapper.eq("publish_status",status);
        }


        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),spuInfoEntityQueryWrapper

        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {

        //根据spu查询出来
        SpuInfoEntity spuInfoEntity = this.baseMapper.selectById(spuId);
        BrandEntity brandEntity = brandService.getById(spuInfoEntity.getBrandId());
        CategoryEntity categoryEntity = categoryService.getById(spuInfoEntity.getCatalogId());


        //根据spuId查询出来所有的属性
        List<ProductAttrValueEntity> entities = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));

        List<Long> attrIds = entities.stream().map(
                item ->item.getAttrId()

        ).collect(Collectors.toList());

        //所有的可以检索的ids
        List<Long> searchAttrIds =attrService.selectSerchAttrIds(attrIds);
        Set<Long> idSet=new HashSet<Long>(searchAttrIds);

        List<SkuEsModel.Attrs> attrValueEntities = entities.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item->{
            SkuEsModel.Attrs attrs=new SkuEsModel.Attrs();
            attrs.setAttrId(item.getAttrId());
            attrs.setAttrName(item.getAttrName());
            attrs.setAttrValue(item.getAttrValue());
            return attrs;
        }).collect(Collectors.toList());

        //获取sku信息
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));

        List<Long> skuidList = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        //查询是否有库
        List<SkuHasStockVo> skuHasStockVos=new ArrayList<SkuHasStockVo>();

        R<List<SkuHasStockVo>> r =wareFeignService.getSkusHasStock(skuidList);
        if(r.getCode()==0){
           skuHasStockVos= r.getData(new TypeReference<List<SkuHasStockVo>>(){});
//           skuHasStockVos = new ObjectMapper().convertValue(skuHasStockVos, new TypeReference<List<SkuHasStockVo>>(){});
        }

        Map<Long, Boolean> map = skuHasStockVos.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::isHasStock));
      /*  Map<Long, Boolean> map =new HashMap<>();
        for(SkuHasStockVo item:skuHasStockVos){
            map.put(item.getSkuId(),item.isHasStock());
        }*/

        List<SkuEsModel> skuEsModels = skuInfoEntities.stream().map(
                item -> {
                    SkuEsModel skuEsModel = new SkuEsModel();
                    BigDecimal price = item.getPrice();
                    Long skuId = item.getSkuId();
                    String skuName = item.getSkuName();

                    skuEsModel.setSkuId(skuId);
                    skuEsModel.setSpuId(spuId);
                    skuEsModel.setSkuTitle(item.getSkuTitle());
                    skuEsModel.setSkuPrice(price);
                    skuEsModel.setSkuImg(item.getSkuDefaultImg());
                    skuEsModel.setSaleCount(item.getSaleCount());
                    //远程调用库存系统查询是否有库存
                    Boolean aBoolean = map.get(skuId);
                    skuEsModel.setHosStock(aBoolean == null ? false : aBoolean.booleanValue());

                    skuEsModel.setHotScore(0L);
                    skuEsModel.setBrandId(item.getBrandId());
                    skuEsModel.setCatelogId(item.getCatalogId());

                    skuEsModel.setBrandName(brandEntity.getName());
                    skuEsModel.setBrandImg(brandEntity.getLogo());

                    skuEsModel.setCatalogName(categoryEntity.getName());

                    //
                    skuEsModel.setAttrs(attrValueEntities);


                    return skuEsModel;
                }
        ).collect(Collectors.toList());

        try {
            System.out.println(new ObjectMapper().writeValueAsString(skuEsModels));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }


        R esR=searchFeignService.productStatusUp(skuEsModels);
        if(esR.getCode()==0){
            //修改spu的状态
            SpuInfoEntity spuInfoEntity1=new SpuInfoEntity();
            spuInfoEntity1.setId(spuId);
            spuInfoEntity1.setUpdateTime(new Date());
            spuInfoEntity1.setPublishStatus(1);

            this.updateById(spuInfoEntity1);

        }


    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        //1、保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity=new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        //2、保存spu的描述图片  pms_spu_info_desc

        List<String> decript = spuSaveVo.getDecript();

        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",",decript));

        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);
        //3、保存spu的图片集  pms_spu_images
        List<String> images = spuSaveVo.getImages();

        spuImagesService.saveImages(spuInfoEntity.getId(),images);

        //4、保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        productAttrValueService.saveBaseAttrs(spuInfoEntity.getId(),baseAttrs);

        //6、 spu的积分信息：sms_spu_bounds


        //5、保存当前spu对应的所有sku信息

        //5。1、sku的基本信息 pms_sku_info
//        List<SkuImagesEntity> collect =new ArrayList<SkuImagesEntity>();
        List<Skus> skus = spuSaveVo.getSkus();
        if(skus!=null && skus.size()>0) {
            skus.forEach(item -> {

               String defaultImgUrl="";

                for( Images img :item.getImages()){
                    if(img.getDefaultImg()==1){
                        defaultImgUrl=img.getImgUrl();
                    }
                }


                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImgUrl);
                skuInfoService.save(skuInfoEntity);

                //5。2、保存sku的图片信息 pms_sku_images
                //TODO 没有图片路径的无需保存
                Long skuId=skuInfoEntity.getSkuId();
                List<SkuImagesEntity> collect = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());

                    return skuImagesEntity;

                }).filter(entity->!StringUtils.isEmpty(entity.getImgUrl())
                ).collect(Collectors.toList());

                skuImagesService.saveBatch(collect);

                //5。3、保存sku的销售属性 pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();

                List<SkuSaleAttrValueEntity> collect1 = attr.stream().map(att -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);

                    return skuSaleAttrValueEntity;

                }).collect(Collectors.toList());

                skuSaleAttrValueService.saveBatch(collect1);


                //5。4、sku的优惠、满减等信息 sms_sku_ladder、sms_sku_full_reduction、sms_member_price

                SkuReductionTo skuReductionTo=new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if(skuReductionTo.getFullCount()>0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal(0))==1){
                    R r1 =couponFeignService.saveSkuReduction(skuReductionTo);
                    if(r1.getCode()!=0){
                        log.error("远程保存spu优惠信息失败");
                    }

                }

            });
            Bounds bound = spuSaveVo.getBounds();
            SpuBoundDTo spuBoundDTo = new SpuBoundDTo();
            spuBoundDTo.setBuyBounds(bound.getBuyBounds());
            spuBoundDTo.setGrowBounds(bound.getGrowBounds());
            spuBoundDTo.setSpuId(spuInfoDescEntity.getSpuId());
            R r =couponFeignService.saveSpuBounds(spuBoundDTo);
            if(r.getCode()!=0){
                log.error("远程保存spu积分信息失败");
            }

        }




    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }


}